package com.binguo.wxapi.controller;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.exception.ServiceException;
import com.binguo.common.util.DateUtil;
import com.binguo.common.util.JsonUtil;
import com.binguo.model.api.vo.*;
import com.binguo.model.mapper.ShopConfigExtendMapper;
import com.binguo.model.model.BinguoOrder;
import com.binguo.model.model.PayCard;
import com.binguo.model.model.ProductSourceInfo;
import com.binguo.model.repository.PayCardRepository;
import com.binguo.model.wxapi.vo.SideBoardVO;
import com.binguo.service.CustomerService;
import com.binguo.service.OrderService;
import com.binguo.service.YpCardService;
import com.binguo.wxapi.form.MeshProductOrderForm;
import com.binguo.wxapi.result.Result;
import com.binguo.wxapi.result.ResultGenerator;
import com.binguo.wxapi.service.WXCustomerService;
import com.binguo.wxapi.vo.ProductSourceInfoVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import io.swagger.models.auth.In;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import static com.binguo.common.exception.ErrorCode.WX_PAYCARD_NOT_EXIST;
import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;


/**
 * Created by haibang on 18/5/7.
 */
@Api(tags = "小程序: 订单")
@RestController
@RequestMapping
public class WXOrderController {

    private static Logger logger = LoggerFactory.getLogger(WXOrderController.class);

    @Autowired
    OrderService orderService;

    @Autowired
    WXCustomerService wxCustomerService;

    @Autowired
    CustomerService customerService;

    @Autowired
    PayCardRepository payCardRepository;



    BigDecimal carilo = new BigDecimal(4.184);

    java.text.DecimalFormat df = new java.text.DecimalFormat("#.00");



    @PostMapping(value = "/api/wxapp/meshproduct/order")
    @ApiOperation(value = "在线订餐下单")
    public Result getCustomerGroup(@RequestBody MeshProductOrderForm form) {
        String imgJson = null;
        try {
            imgJson = JsonUtil.toJson(form);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        System.out.println(imgJson);

        wxCustomerService.meshOrder(form);

        return ResultGenerator.genSuccessResult();
    }

    @GetMapping(value = "/api/wxapp/order/detail/{customerId}/{orderNo}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取单个订单", notes = "通过customerId,orderNo")
    public Result getOrder(@PathVariable Integer customerId, @PathVariable String orderNo) {
        OrderVO vo = orderService.findOneByCustomerIdAndOrderNo(customerId, orderNo);
        if(vo == null){
            return ResultGenerator.genFailResult("订单不存在");
        }
        if (StringUtils.isEmpty(vo.getProductOrderUrl())) {
            if (StringUtils.hasText(vo.getSerialNumber())) {
                vo.setProductOrderUrl("http://m.binguoai.com/" + vo.getSerialNumber() + ".jpg");
            }
        }
        //SideBoardVO sideBoard =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        if (vo.getOrderItems() != null && vo.getOrderItems().size() > 0) {

            BigDecimal count = new BigDecimal(0);
            for (OrderItemVO orderItemVO : vo.getOrderItems()) {
                String calorie = orderItemVO.getCalorie();

                if (StringUtils.hasText(calorie)) {
                    count = count.add(new BigDecimal(calorie));
                }
            }
            if (count.compareTo(new BigDecimal(0)) > 0) {
                count = count.divide(carilo, RoundingMode.HALF_UP);
                Nutrition nutrition = new Nutrition();
                nutrition.setName("热量");
                nutrition.setCount(df.format(count) + "大卡/100g");
                vo.setNutritionList(new ArrayList<>());
                vo.getNutritionList().add(nutrition);
            }
        }

        return ResultGenerator.genSuccessResult(vo);
    }


    @GetMapping(value = "/api/wxapp/order/product/{productId}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取产品详情", notes = "通过productId")
    public Result getOrder(@PathVariable Integer productId) {

        ProductSourceInfo productSourceInfo = orderService.getProductSourceInfo(productId);

        return ResultGenerator.genSuccessResult(productSourceInfo);
    }

    @GetMapping(value = "/api/wxapp/order/list/{customerId}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取订单列表", notes = "通过客户id,最后一条订单号")
    public Result getOrders(@PathVariable Integer customerId,
                            @ApiParam("最后一条订单号") @RequestParam Optional<String> lastOrderNo,
                            @ApiParam("搜索key") @RequestParam Optional<String> searchKey) {
        List<OrderVOInWX> list = orderService.findWXOrders(customerId, lastOrderNo, searchKey);

        if (list != null && list.size() > 0) {
            for (OrderVOInWX orderVO : list) {
                if (orderVO.getOrderType() != null &&
                        orderVO.getOrderType() == 3) {

                    orderVO.setShopName("订餐取票号:" + orderVO.getSerial() + "-" + orderVO.getShopName());
                }
            }
        }
        return ResultGenerator.genSuccessResult(list);
    }


    @GetMapping(value = "/api/wxapp/order/list/shop/{shopId}/{branchId}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取订单列表", notes = "通过客户id,最后一条订单号")
    public Result getShopOrders(@PathVariable Integer shopId,
                                @PathVariable Integer branchId,
                                @ApiParam("最后一条订单号") @RequestParam Optional<String> lastOrderNo,
                                @ApiParam("是否存餐") @RequestParam Integer isMeal,
                                @ApiParam("搜索key") @RequestParam Optional<String> searchKey) {
        if (isMeal.equals(2)){
            isMeal = null;
        }
        List<OrderVOInWX> list = orderService.findShopOrders(shopId,branchId, lastOrderNo, searchKey,isMeal);

        return ResultGenerator.genSuccessResult(list);
    }
    @GetMapping(value = "/api/wxapp/order/detail/{orderNo}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取单个订单", notes = "orderNo")
    public Result getOrder( @PathVariable String orderNo) {
        OrderVO vo = orderService.findOneByOrderNo(orderNo);

        if (StringUtils.isEmpty(vo.getProductOrderUrl())) {
            if (StringUtils.hasText(vo.getSerialNumber())) {
                vo.setProductOrderUrl("http://m.binguoai.com/" + vo.getSerialNumber() + ".jpg");
            }
        }
        //SideBoardVO sideBoard =  shopConfigExtendMapper.selectByShopIdAndBranchId(form.getShopId(),form.getBranchId());
        if (vo.getOrderItems() != null && vo.getOrderItems().size() > 0) {

            BigDecimal count = new BigDecimal(0);
            for (OrderItemVO orderItemVO : vo.getOrderItems()) {
                String calorie = orderItemVO.getCalorie();

                if (StringUtils.hasText(calorie)) {
                    count = count.add(new BigDecimal(calorie));
                }
            }
            if (count.compareTo(new BigDecimal(0)) > 0) {
                count = count.divide(carilo, RoundingMode.HALF_UP);
                Nutrition nutrition = new Nutrition();
                nutrition.setName("热量");
                nutrition.setCount(df.format(count) + "大卡/100g");
                vo.setNutritionList(new ArrayList<>());
                vo.getNutritionList().add(nutrition);
            }
        }

        return ResultGenerator.genSuccessResult(vo);
    }


    @GetMapping(value = "/api/wxapp/reserveOrder/todayList", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取订单列表", notes = "通过客户id,最后一条订单号")
    public Result getTodayList(@RequestParam @NotNull Integer customerId,
                               @RequestParam @NotNull Integer shopId,
                               @RequestParam String cardNo,
                               @RequestParam String qrcode) {

        if (customerId.equals(0)){
            if (!cardNo.equals("0")){
                PayCard payCard = customerService.getYpCard(cardNo,shopId);
                customerId = payCard.getCustomerid();
            }else if (!qrcode.equals("0")){
                Condition condition = new Condition(PayCard.class);
                condition.or()
                        .andEqualTo("payCode", qrcode);
                PayCard payCard = payCardRepository.findByCondition(condition).stream().findFirst().orElseThrow(() -> new ServiceException(WX_PAYCARD_NOT_EXIST));
                customerId = payCard.getCustomerid();
            }else {
                throw new ServiceException("参数错误");
            }

        }
        List<OrderVOInWX> list = orderService.getTodayOrderByCustomerId(customerId,shopId);

        return ResultGenerator.genSuccessResult(list);
    }

    @PostMapping(value = "/api/wxapp/reserveOrder/pay")
    @ApiOperation(value = "在线订餐下单")
    public Result reserveOrderPay(@RequestBody JSONObject jsonObject) {
        String orderNo = jsonObject.getString("orderNo");
        orderService.reserveOrderPay(orderNo);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping(value = "/api/wxapp/reserveOrder/{branchId}", produces = APPLICATION_JSON_VALUE)
    @ApiOperation(value = "获取产品详情", notes = "通过productId")
    public Result sumReserveOrder(@PathVariable Integer branchId) {
        return ResultGenerator.genSuccessResult(orderService.getTodayReserveOrder(branchId));
    }
}
